package com.android.inputmethod.pinyin;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Admin on 2018/2/7.
 */

public class TrieTree {

    char letterChar = 0;

    List<Letter> letters = null;

    List<TrieTree> childNodes = null;


    public TrieTree()
    {

    }
    public TrieTree(char c)
    {
        letterChar = c;
    }

    public void addLetter(Letter letter,String spl)
    {
        if( 0 < spl.length())
        {
            char c = spl.charAt(0);
            if(childNodes == null)
            {
                childNodes = new ArrayList<>();
            }
            TrieTree child;
            if((child=inChildPos(c)) == null)
            {
                child = new TrieTree(c);
                childNodes.add(child);
            }
            spl = spl.substring(1,spl.length());
            if(spl.length() == 0)
            {
                if(child.letters == null)
                {
                    child.letters = new ArrayList<>();
                }
                if(!containsLetter(child.letters,letter))
                    child.letters.add(letter);
                return;
            }
            child.addLetter(letter,spl);
        }
    }

    private boolean containsLetter(List<Letter> letters,Letter letter)
    {
        for(Letter l:letters)
        {
            if(l.letter == letter.letter && l.freq == letter.freq) return true;
        }
        return false;
    }
    private TrieTree getPrefixNode(String prefix)
    {
        if(prefix.length() == 0) return this;
        TrieTree node = inChildPos(prefix.charAt(0));
        if(node == null) return null;
        return node.getPrefixNode(prefix.substring(1,prefix.length()));
    }

    private void addLettersToList(List<Letter> subLetters,int layer,int max)
    {
        if(subLetters.size() >= max) return;
        if(layer == 0) return;
        if(letters != null)
            subLetters.addAll(letters);
        layer--;
        for(int i=0;childNodes != null && i<childNodes.size();i++)
        {
            childNodes.get(i).addLettersToList(subLetters,layer,max);
        }
    }

    public List<Letter> getAllSubLetters(List<Letter> subLetters,String spl,int layer,int max)
    {
        TrieTree prefixNode = getPrefixNode(spl);
        TrieTree node = prefixNode;
        if(node != null)
        {
            node.addLettersToList(subLetters,layer,max);
        }

        return subLetters;
    }

    private TrieTree inChildPos(char c)
    {
        if(childNodes == null) return null;
        for(TrieTree tree:childNodes)
        {
            if(tree.letterChar == c)
                return  tree;
        }
        return null;
    }


}
